package com.stars.module.department.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stars.base.constants.CommonNumberConstants;
import com.stars.base.entity.CommonDTO;
import com.stars.base.entity.TreeNode;
import com.stars.module.department.entity.StarDept;
import com.stars.module.department.mapper.StarDeptMapper;
import com.stars.module.department.service.StarDeptService;
import com.stars.util.common.DevelopKit;
import com.stars.util.tree.TreeNodeUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @author : mango
 * @version : 1.0
 * @date : 2022/10/31 11:20
 * @description : 部门服务接口实现类
 */
@Service
public class StarDeptServiceImpl implements StarDeptService {
    private final StarDeptMapper deptMapper;

    public StarDeptServiceImpl(StarDeptMapper deptMapper) {
        this.deptMapper = deptMapper;
    }

    //获取所有部门
    @Override
    public JSONObject loadDeptByFid(CommonDTO dto) {

        Page<StarDept> page = Page.of(dto.getCurrent(), dto.getPageSize());

        LambdaQueryWrapper<StarDept> wrapper = new LambdaQueryWrapper<>();

        wrapper.like(StarDept::getOrgName,dto.getSearch());
        wrapper.eq(StarDept::getFid, dto.getFid());
        wrapper.eq(StarDept::getIsUnit,-1);
        wrapper.orderByAsc(StarDept::getShowOrder);

        JSONObject result = new JSONObject();

        Page<StarDept> systemDefineEntityPage = deptMapper.selectPage(page, wrapper);

        result.put("list",systemDefineEntityPage.getRecords());
        result.put("total",systemDefineEntityPage.getTotal());

        return result;
    }

    /**
     * @author : mango
     * @date : 2023/2/27 17:06
     * @description : 加载部门树
     */
    @Override
    public JSONArray loadAllDept() {
        JSONArray array = new JSONArray();

        List<StarDept> allDeptArr = Optional.ofNullable(deptMapper.selectList(null)).orElse(Collections.emptyList());

        List<TreeNode> treeNodes = new ArrayList<>();

        for(StarDept dept : allDeptArr){

            TreeNode node = new TreeNode();
            node.setValue(dept.getId());
            node.setpId(dept.getFid());
            node.setLabel(dept.getOrgName());

            treeNodes.add(node);
        }

        TreeNode root = new TreeNode(CommonNumberConstants.ZERO_STR,"部门管理",CommonNumberConstants.MINUS_ONE_STR);

        array.add(TreeNodeUtil.merge(root,treeNodes).toJSON());

        return array;
    }

    @Override
    public JSONObject loadAllDeptByUnitId(String unitId,String fid) {
        JSONObject object = new JSONObject();

        LambdaQueryWrapper<StarDept> wrapper = new LambdaQueryWrapper<>();

        if("0".equals(fid)){
            wrapper.eq(StarDept::getId,unitId);
        }else{
            wrapper.eq(StarDept::getFid,fid);
            wrapper.eq(StarDept::getIsUnit,"-1");
        }

        List<StarDept> allDeptArr = Optional.ofNullable(deptMapper.selectList(wrapper)).orElse(Collections.emptyList());

        List<TreeNode> treeNodes = new ArrayList<>();

        for(StarDept dept : allDeptArr){

            TreeNode node = new TreeNode();
            node.setValue(dept.getId());
            node.setpId(dept.getFid());
            node.setLabel(dept.getOrgName());

            treeNodes.add(node);
        }

        object.put("data",treeNodes);
        return object;
    }

    @Override
    public StarDept loadDeptById(String deptId) {
        return deptMapper.selectById(deptId);
    }

    @Override
    public boolean saveOrUpdateDept(StarDept dept) {

        if(StringUtils.hasLength(dept.getId())){
            //有ID，更新
            return deptMapper.updateById(dept) > 0;
        }else{
            //无ID，新增
            dept.setId(DevelopKit.generateUUID());

            DevelopKit.setBaseInfo(dept);

            return deptMapper.insert(dept) > 0;
        }
    }

    @Override
    public boolean removeDept(String id) {
        LambdaQueryWrapper<StarDept> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StarDept::getFid,id);

        if(deptMapper.exists(wrapper)){
            return false;
        }
        return deptMapper.deleteById(id)>0;
    }

    @Override
    public Integer getMaxIndex(String fid,String unitId) {
        QueryWrapper<StarDept> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(StarDept::getFid,fid)
                .eq(StarDept::getUnitId,unitId);

        queryWrapper.select("MAX(SHOWORDER) AS SHOWORDER");
        StarDept starDept = deptMapper.selectOne(queryWrapper);

        return starDept!=null?starDept.getShowOrder():0;
    }

    @Override
    public StarDept loadUserMainDept(String userId) {
        return deptMapper.loadUserMainDept(userId);
    }
}
